package tk.mybatis.springboot.service.impl;

import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StatusRootService {

    public static final String URL = "jdbc:mysql://localhost:3306/root";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "root";

    public List<Map<String,Object>> selectPageByStatus(Integer page,Integer count,Integer tab){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        Integer offset = (page - 1) * count;
        String condition = "";
        if (tab==1) {
            condition = " and task_result = 0 or task_result = 4 ";
        } else if (tab==2) {
            condition = " and task_result = 2 or task_result = 5 ";
        } else if (tab==3) {
            condition = " and task_result = 1 ";
        }

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
            String sql = "select task_result,task_name from rt_task_data where 1=1 "
                    +condition
                    +" order by task_start_date desc LIMIT ?, ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,offset);
            statement.setInt(2,count);
            resultSet = statement.executeQuery();
            List<Map<String,Object>> maps = new ArrayList<>();
            while (resultSet.next()){
                Map<String,Object> queryRoot = new HashMap<>();
                Integer task_result = resultSet.getInt("task_result");
                if(task_result == 0){
                    queryRoot.put("Status","idle");
                } else if (task_result == 1) {
                    queryRoot.put("Status","finish");
                } else if (task_result == 2) {
                    queryRoot.put("Status","aborted");
                } else if (task_result == 4) {
                    queryRoot.put("Status","running");
                } else if (task_result == 5) {
                    queryRoot.put("Status","paused");
                }
                String task_name = resultSet.getString("task_name");
                    queryRoot.put("TaskNo",task_name);
                maps.add(queryRoot);
            }
            return maps;
        } catch (Exception e) {
            System.out.println("查询科聪的表失败："+ e.getMessage());
            throw new RuntimeException(e);
        }finally {
            try {
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        }

    }
}
